package com.banmao.snake_core.util;

import cn.hutool.core.io.IORuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

@Slf4j
public class FileUtil {

    public static boolean saveTextToFile(String fileName, String text, String directoryPath) {
        String filePath = "";
        try {
            filePath = getFilePath(fileName, directoryPath);
            log.info("向文件 {} 写入数据", filePath);
            cn.hutool.core.io.FileUtil.writeString(text, filePath, "UTF-8");
            return true;
        } catch (URISyntaxException e) {
            //throw new RuntimeException(e);
            log.error("向文件 {} 写入数据失败, error:", filePath, e);
            return false;
        }
    }

    private static String getFilePath(String fileName, String directoryPath) throws URISyntaxException {
        URI uri = Objects.requireNonNull(FileUtil.class.getResource("/")).toURI();
        File directory = new File(uri.getPath() + File.separator + directoryPath);
        // 持久化文本
        if(!directory.exists()) {
            // 文件夹不存在，进行创建
            cn.hutool.core.io.FileUtil.mkdir(directory);
        }
        return directory.getAbsolutePath() + File.separator + fileName;
    }

    public static void main(String[] args) throws Exception {
        //URI uri = Objects.requireNonNull(FileUtil.class.getResource("/")).toURI();
        //String path = uri.getPath();
        //System.out.println(path);
        ////path = UrlBuilder.of(path).addPath("a.txt").build();
        ////System.out.println(path);
        //File file = new File(path);
        //System.out.println(file.getAbsolutePath());
        //System.out.println(file.isFile());
        //System.out.println(file.isDirectory());

        boolean b = FileUtil.saveTextToFile("banmao", "你好啊", "static/token");
        System.out.println(b);
    }

    public static String readText(String fileName, String directoryPath) {
        try {
            String text = cn.hutool.core.io.FileUtil.readString(getFilePath(fileName, directoryPath), StandardCharsets.UTF_8);
            return text;
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        } catch (IORuntimeException e2) {
            if(StringUtils.contains(e2.getMessage(), "File not exist")) {
                return null;
            }
        }
        return null;
    }

}
